/*
 * Copyright (C) 2003-2008 Wang Pengcheng <wpc0000@gmail.com>
 * Permission is granted to copy, distribute and/or modify this
 * document under the terms of the GNU Free Documentation License,
 * Version 2.0 or any later version published by the Free Software Foundation;
 * with no Invariant Sections.
 * You may obtain a copy of the License at
 *   http://www.gnu.org/licenses/lgpl.txt
 */
//May 5, 2008

package cn.edu.whu.control;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import cn.edu.whu.data.Data;
import cn.edu.whu.data.DataList;
import cn.edu.whu.data.VarList;

public class EditDBSQL {
	private static String fileUrl =
		BasicDataForEdit.TEMPLATE_FILE_DIR+
		"db/create.sql";
	private static String SALE_FILE_NAME = "create_.sql";
	
	private VarList varList;
	private DataList dataList;
	
	
	private String fileData="";
	
	public void read() throws Exception{
		FileInputStream storageFile;

			storageFile = new FileInputStream(fileUrl);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					storageFile));
			while(true){
				String s = in.readLine();
				if(s==null){
					break;
				}
				fileData +=s+"\n";
			}
	}
	
	public void change(){
		String res ="";
		String pk="PRIMARY KEY(";
		boolean f = true;
		for(Data d:dataList){
			//TOOD Set the auto_increment id
			if(d.getName().toLowerCase().contains("id")&&f){
				pk +=d.getDatabaseName()+")";
				res+=d.getDatabaseName()+" INTEGER NOT NULL AUTO_INCREMENT";
				f=false;
			}else{
				String type = BasicDataForEdit.getDatabaseType(d.getType());
				res+=d.getDatabaseName()+" "+type;
			}
			res+=",\n";
		}
		res+=pk;
		varList.setValue("$DBCREATEINFOR", res);
		//System.err.println(varList.getValue("$DBCREATEINFOR"));
		for(int i=0;i<varList.length();i++){
			//System.err.println(varList.getVar(i));
			fileData=fileData.replace(varList.getVar(i), varList.getValue(i));
			//System.err.println(fileData);
		}
	}
	
	public void setPath(String path){
		SALE_FILE_NAME = path;
	}
	
	public void write() throws Exception{
		FileOutputStream saleFile = new FileOutputStream(SALE_FILE_NAME);
		BufferedWriter out = new BufferedWriter(
				new OutputStreamWriter(saleFile));
		out.flush();
		out.newLine();
		out.append(fileData);
		out.close();
	}

	public EditDBSQL(VarList varList, DataList dataList) {
		super();
		this.varList = varList;
		this.dataList = dataList;
	}
}

